﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using KOF.Helpers;
using Newtonsoft.Json;
using Microsoft.Phone.Net.NetworkInformation;

namespace KOF.Views
{
    public partial class BrandView : PhoneApplicationPage
    {
        
        public BrandView()
        { //This Code checks internet Connection
            if (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
            {

            }
            else
            {
                MessageBox.Show("Please check your internet connection!");
            }
            InitializeComponent();
            List.ItemsSource = ListItemSource;
            try
            {
                GetAllBrands();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        // Get Brands From WebService
        public void GetAllBrands()
        {
            try
            {
                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
                wc.DownloadStringAsync(new Uri("http://app.kicksonfire.com/kofapp/index.php/api/events/GetEventTypes"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
               

                if (ListItemSource == null) ListItemSource = new ObservableCollection<ResponseBrand>();
                //Adding all option 
                ListItemSource.Add(new ResponseBrand() { brand_name = "All", id = "0", showBrandName = true, showSubItems = false, checked1 = false });

                // Parse Json
                var deserialized = JsonConvert.DeserializeObject<ServiceResult>(e.Result);
                foreach (KOF.Helpers.ResponseBrand a in deserialized.types)
                {
                    if (a.subtypes != null && a.subtypes.Count > 0)
                    {
                        a.showSubItems = true;
                        a.showBrandName = true;

                        if ((App.Current as App).gSelectedBrands != null && (App.Current as App).gSelectedBrands.Count > 0)
                        {
                            foreach (ResponseBrand sub in a.subtypes)
                            {
                                ResponseBrand sV = (from b in (App.Current as App).gSelectedBrands
                                          where b.id == sub.id 
                                          select b).FirstOrDefault();
                                if (sV != null)
                                {
                                    sub.checked1 = true;
                                    sub.showBrandName = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        a.showSubItems = false;
                        a.showBrandName = true;
                    }


                    // Select Checked Brands From Application Storage
                    if ((App.Current as App).gSelectedBrands != null && (App.Current as App).gSelectedBrands.Count > 0)
                    {
                        var v = (from b in (App.Current as App).gSelectedBrands
                                 where b.brand_name == a.brand_name
                                 select b).SingleOrDefault();
                        if (v != null)
                        {
                            a.checked1 = true;
                        }
                    }
                    ListItemSource.Add(a);
                }



                //code to see whether all brands are selected or not
                var tt = from a in ListItemSource
                         where a.brand_name != "All" && a.checked1 == true
                         select a;

                if (tt != null && tt.Count() == ListItemSource.Count - 1)
                {
                    var allOPtion = (from a in ListItemSource
                                     where a.brand_name == "All"
                                     select a).FirstOrDefault();
                    if (allOPtion != null) allOPtion.checked1 = true;
                }

                List.ItemsSource = null;
                List.ItemsSource = ListItemSource;
               
                prgtext.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }


        private ObservableCollection<ResponseBrand> _listItemSource;
        public ObservableCollection<ResponseBrand> ListItemSource
        {
            
            get
            {
                
                return _listItemSource;
            }
            set
            {
                if (_listItemSource != value)
                {
                    _listItemSource = value;
                }
               
            }
       
        }

        //Save Selected Brands to Application Storage when Back Button is Pressed.
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                {
                    if (List.Items.Count > 0)
                    {
                        (App.Current as App).gSelectedBrands.Clear();
                        
                       
                        foreach (KOF.Helpers.ResponseBrand itm in List.ItemsSource)
                        {
                            KOF.Helpers.ResponseBrand newRec = new Helpers.ResponseBrand();
                            newRec.id = itm.id;
                            newRec.brand_name = itm.brand_name;
                            newRec.subtypes = itm.subtypes;
                            if (itm.checked1) (App.Current as App).gSelectedBrands.Add(newRec);

                            if (itm.subtypes != null && itm.subtypes.Count > 0)
                            {
                                foreach (ResponseBrand sub in itm.subtypes)
                                {
                                    if (sub.checked1) (App.Current as App).gSelectedBrands.Add(sub);
                                }
                            }
                          
                        }
                       
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            base.OnNavigatedFrom(e);
        }


        private void chkTest_Checked(object sender, RoutedEventArgs e)
        {
            try
            {

                // Code when All Checkbox is checked
                CheckBox chk = sender as CheckBox;
                if (chk.Tag == null) return;
                if (chk.Tag.ToString() == "All")
                {
                   
                    foreach (ResponseBrand brand in ListItemSource)
                    {
                        brand.checked1 = true;
                        if (brand.subtypes != null && brand.subtypes.Count > 0)
                        {
                            foreach (ResponseBrand subBrand in brand.subtypes)
                            {
                                subBrand.checked1 = true;
                            }
                        }
                    }
                }
                else
                {

                    // code to see whether all brands are selected or not
                   
                    int intCheckedItemsCount = 0;
                    var vMainBrands = from a in ListItemSource
                                      where a.brand_name != "All" && a.checked1 == true && (a.subtypes == null || a.subtypes.Count == 0)
                                      select a;

                    intCheckedItemsCount += vMainBrands.Count();

                    var vSubBrands = from s in ListItemSource
                                     where s.brand_name != "All" && s.subtypes != null && s.subtypes.Count > 0
                                     select s;

                    if (vSubBrands != null && vSubBrands.Count() > 0)
                    {
                        foreach (ResponseBrand BrandContainingSubBrands in vSubBrands)
                        {
                            

                            var test = from sCount in BrandContainingSubBrands.subtypes
                                       where sCount.checked1 == true
                                       select sCount;
                            if (test != null && test.Count() > 0)
                            {
                                intCheckedItemsCount += test.Count();
                            }
                          

                            if (chk.Tag.ToString() == BrandContainingSubBrands.brand_name)
                            {
                                intCheckedItemsCount = intCheckedItemsCount + 1;
                            }
                        }
                    }

                   
                    if (intCheckedItemsCount == (ListItemSource.Count - vSubBrands.Count()))
                    {
                        var allOPtion = (from a in ListItemSource
                                         where a.brand_name == "All"
                                         select a).FirstOrDefault();
                        if (allOPtion != null) allOPtion.checked1 = true;
                    }
                }
                //code for subbrands checked
                if (chk.Tag != null)
                {
                    foreach (ResponseBrand brand in ListItemSource)
                    {
                        
                        //brand.checked1 = true;
                        if (brand.subtypes != null && brand.subtypes.Count > 0)
                        {   
                            foreach (ResponseBrand subBrand in brand.subtypes)
                            {
                                if (chk.Tag.ToString() == brand.brand_name.ToString())
                                {
                                    subBrand.checked1 = true;
                                }
                                if (chk.Tag.ToString() == subBrand.brand_name.ToString())
                                {
                                    subBrand.checked1 = true;
                                }

                            }
  
                        }


                        // code to select main brand based on subbrands selected like Nike All.

                        if (brand.subtypes != null && brand.subtypes.Count > 0)
                        { 
                            int i = 0;
                            foreach (ResponseBrand subBrand in brand.subtypes)
                            {
                               

                                if (subBrand.checked1 == false)
                                {
                                    i = 1;
                                    break;
                                }

                            }

                            if (i == 0)
                            {
                                brand.checked1 = true;
                            }
                            else
                            {
                                brand.checked1 = false;
                            }

                        }
                     
                       
                    }
                }
                //code
                List.ItemsSource = null;
                List.ItemsSource = ListItemSource;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void chkTest_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox chk = sender as CheckBox;
                if (chk.Tag == null) return;
                if (chk.Tag.ToString() == "All")
                {
                    foreach (ResponseBrand brand in ListItemSource)
                    {
                        brand.checked1 = false;
                        if (brand.subtypes != null && brand.subtypes.Count > 0)
                        {
                            foreach (ResponseBrand subBrand in brand.subtypes)
                            {
                                subBrand.checked1 = false;
                            }
                        }
                    }
                }
                else
                {
                    var v = (from a in ListItemSource
                             where a.brand_name == "All"
                             select a).FirstOrDefault();

                    if (v != null)
                    {
                        v.checked1 = false;
                    }

                    // my code
                    if (chk.Tag != null)
                    {
                        foreach (ResponseBrand brand in ListItemSource)
                        {

                            //brand.checked1 = true;
                            if (brand.subtypes != null && brand.subtypes.Count > 0)
                            {
                                foreach (ResponseBrand subBrand in brand.subtypes)
                                {
                                    if (chk.Tag.ToString() == brand.brand_name.ToString())
                                    {
                                        subBrand.checked1 = false;
                                    }
                                    if (chk.Tag.ToString() == subBrand.brand_name.ToString())
                                    {
                                        subBrand.checked1 = false;
                                    }

                                }

                            }




                            if (brand.subtypes != null && brand.subtypes.Count > 0)
                            {
                                int i = 0;
                                foreach (ResponseBrand subBrand in brand.subtypes)
                                {


                                    if (subBrand.checked1 == false)
                                    {
                                        i = 1;
                                        break;
                                    }

                                }

                                if (i == 0)
                                {
                                    brand.checked1 = true;
                                }
                                else
                                {
                                    brand.checked1 = false;
                                }

                            }

                        }

                        // complete

                    }
                }
                List.ItemsSource = null;
                List.ItemsSource = ListItemSource;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }
        

        // Go Bak
        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.NavigationService.GoBack();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }
}